package com.example.demo.javatest.jdk8;


import cn.hutool.core.date.DateUtil;
import com.facebook.ads.sdk.*;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.rmi.RemoteException;
import java.util.*;
import java.util.Date;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * Created by Madhouse on 2019/6/20.
 */
public class FacebookApiTest {
    Logger logger = LoggerFactory.getLogger(FacebookApiTest.class);

    private static int PAGE_SIZE=100;
    private static ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
    public static final APIContext context = new APIContext(
            "EAANXwITyKJ4BAPB0T5RJQ7VqTgDvd6UGLx3H4NGsTzNgCJV6nWzSQvpjmK4Ul2waWUmY2ruVkpi9Ro38mwPZAeScgruvxEGmwTqS7dEyWWo3rA0fib8YqCKZCl9rtRnblqhBNdle5OdZAerChlyeAIGqjU9j6fwuOKlByJkRAZDZD"

    ).enableDebug(true);
    public static void main(String[] args) throws Exception {
        String dateStr = "2019/12/04";
        Date date = DateUtil.parse(dateStr);
        DateUtil.offsetHour(date,3);
        String format = DateUtil.format(date, "yyyy-MM-dd");
        System.out.println(format);
        //fun3();
        /*try{
            try {
                fixedThreadPool.submit(new Callable<Object>() {

                    @Override
                    public Object call() throws Exception{
                        int i=1/0;
                        //throw new InterruptedException("dasda");
                        return "sss";
                    }
                }).get();
            }catch (Exception e){
                throw  new Exception(e.getCause().getMessage());
            }
            int i=1/0;
        }catch (Exception e){
            System.out.println(e.getMessage());
            System.out.println(e.getLocalizedMessage());
        }*/
       /* List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
// 获取对应的平方数
        List<Integer> squaresList = numbers.stream().limit(4).map( i -> i*i).collect(Collectors.toList());
        List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
        strings.stream().filter(string->string.equals("ss")).count();
        System.out.println(squaresList);*/
    }
    static class test implements Runnable{
        public test(List<List<String>> lists) {
            this.lists = lists;
            count=new CountDownLatch(lists.size());
        }

        private List<List<String>> lists;
        private AtomicInteger size=new AtomicInteger(0);
        private CountDownLatch count;


        @Override
        public void run() {
            ExecutorService fixedThreadPool= Executors.newFixedThreadPool(20);
            fixedThreadPool.execute(() -> {
                System.out.println("mainopen");
                System.out.println(Thread.currentThread().getName()+"初始size值为"+size);
                try {
                    count.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+"其它线程完成size值为"+size);
                fixedThreadPool.shutdown();
            });
            for (int i = 0; i <lists.size() ; i++) {
                List<String> list=lists.get(i);
                final  int j=i;
                fixedThreadPool.execute(() -> {
                    System.out.println("第"+j+"组"+list);
                    for (String s : list) {
                        size.incrementAndGet();
                    }
                    count.countDown();

                });
            }
            /*fixedThreadPool.execute(() -> {
                System.out.println("notmainopen");
                count.countDown();
                size--;
            });
            fixedThreadPool.execute(() -> {
                System.out.println("notmainopen");
                count.countDown();
                size--;
            });
            fixedThreadPool.execute(() -> {
                System.out.println("notmainopen");
                count.countDown();
                size--;
            });
            fixedThreadPool.execute(() -> {
                System.out.println("notmainopen");
                count.countDown();
                size--;
            });*/
        }
    }
    public static void fun4(){
        throw new RuntimeException("123121");
    }
    public static void fun3() throws Exception{
        //com.facebook.ads.sdk.Campaign campaign = com.facebook.ads.sdk.Campaign.fetchById(6123897913301l, context);
        AdAccount account = new AdAccount("712344008863677", context);
        AdVideo.fetchByIds(Arrays.asList("13132123"), Arrays.asList("length", "source","thums"), account.getContext());
        //APINodeList<AdVideo> videos=account.getAdVideos().requestFields(Arrays.asList("length","picture","permalink_url","source")).setParam("id","405799213392754").execute();
        /*APINodeList<AdActivity> adActivity=account.getActivities().requestAllFields().execute().withAutoPaginationIterator(true);
        adActivity.forEach(a-> {
            System.out.println(a.getFieldActorId());
        });*/
        //File f=FileUtil.fileDownload("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1565258815275&di=73017a56264f8e1e85646412795b4603&imgtype=0&src=http%3A%2F%2Fnews.mydrivers.com%2FImg%2F20120227%2F2012022709150416.jpg",".");
        /*File f = new File(System.currentTimeMillis()+".png");
        FileUtils.copyURLToFile(new java.net.URL("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1565258815275&di=73017a56264f8e1e85646412795b4603&imgtype=0&src=http%3A%2F%2Fnews.mydrivers.com%2FImg%2F20120227%2F2012022709150416.jpg"), f);
        AdImage image=account.createAdImage().addUploadFile(f.getName(),f).execute();*/
        //account.getAdImages().requestAllFields().setHashes("f1d2d2599e76df62b23a47885c27d89f").execute();
       // File tempFile = new File("ttt.jpg");
        //FileUtils.copyURLToFile(new java.net.URL("https://www.facebook.com/ads/image/?d=AQIvY8ZqG5hZkVOOo8jD8lU5DAI18a8V8Fe4bgVnf6uN1aCxXOFzbxew4ZOgsb9w6lr-tFRioX8LdJ1612T9TpPnsQkgTe6hVkUs76sm-O5x9fTNrtK2aX6cCZeOd1fpl4M5SRH-o56eR53L6Woy_rA3"), tempFile);
        AdVideo video=account.createAdVideo().setParam("file_url","http://adv.madserving.com/material/0bf09733777ebe85fda283e75ffd1bbe_1562235007_95935712.mp4").execute();
        //AdImage image=account.createAdImage().addUploadFile("jjj2",new File("d:/desert.jpg")).requestFields(Arrays.asList("hash", "height", "status", "url_128", "width", "permalink_url")).execute();
        //tempFile.delete();
        //ListenableFuture<AdImage> future=account.createAdImage().addUploadFile("jjj2",new File("d:/desert.jpg")).executeAsync();
        //*APIRequest<AdAccount> request = new APIRequest<AdAccount>(context, "me", "/adaccounts", "GET", AdAccount.getParser());
        //APINodeList<AdAccount> accounts = (APINodeList<AdAccount>)(request.execute());
        //System.out.println(accounts);
        //根据广告账户找video
        //APINodeList<AdVideo> videos=account.getAdVideos().requestFields(Arrays.asList("length","picture","permalink_url","source")).setParam("id","405799213392754").execute();
        //根据id找video
        //AdVideo video=new AdVideo.APIRequestGet("370486703671902", context).setParam("ids", APIRequest.joinStringList(ids)).requestFields(Arrays.asList("length", "source", "created_time", "updated_time")).execute();
        //APINodeList<VideoThumbnail> thumbnail=video.getThumbnails().execute();
        //APINodeList<VideoThumbnail> thum=new AdVideo.APIRequestGetThumbnails("370486703671902", context).execute();
        //删除video
        //video.delete().execute();
        //APINodeList<AdVideo> video=AdVideo.fetchByIds(Arrays.asList("2412043619032758"),Arrays.asList("length", "source","picture"),account.getContext());
        //APINodeList<VideoThumbnail> thumbnail=video.getThumbnails().execute();
        //查找adccount下的所有图片自动分页设置每页大小
        //AdImage image1= new AdImage.APIRequestGet("712344008863677",context).requestAllFields().execute();
        APINodeList<AdImage> images=account.getAdImages().requestAllFields().setHashes(Arrays.asList("f1d2d2599e76df62b23a47885c27d89f")).setParam("limit",1000).execute().withAutoPaginationIterator(true);
        List<List<String>> lists=new ArrayList<>();
        List<String> list=new ArrayList<>(9);
         Integer count = 1;
        //测试多个线程进行同步
       /* for (AdImage image : images) {
            count++;
            Thread.sleep(100);//查询
           *//* System.out.println(image);
            if(count==100) break;
            if(list.size()>9){
                lists.add(list);
                list=new ArrayList<String>();
            }
            list.add(image.getFieldHash());
            System.out.println(count++);*//*
        }
        System.out.println(count);*/
        //new Thread(new test(lists)).start();
        //fun2();
    }
    public  static  void fun2(){
        HttpHost proxy = new HttpHost("172.16.30.219", 8125, "http");
        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(config).build();
        String url1 = "https://graph.facebook.com/v3.2/me/businesses?access_token=EAAHgEYXO0BABAGcHX8cg9gA1jxA5YPEqk3fnHIJrJS72WttvJkZC0Mc4X9ZBlbUatsjAZCJwhvOMzpA3pm6lTh3pNabAXbLjLcEBCNAvteZCZAvCQQmB48LkcVgPT22uASHH4Fp6ke9cNIH2hgqj8MvNcxNSbAw9evgP0IfMEowZDZD";
        String url3 = "https://graph.facebook.com/v3.2/act_1288367094594696/insights?level=account&time_increment=1&time_range=%7B%22since%22%3A%222019-04-26%22%2C%22until%22%3A%222019-04-29%22%7D&fields=account_id,campaign_id,adset_id,ad_id,impressions,clicks,spend,actions,mobile_app_purchase_roas,date_start,date_stop&access_token=EAAHgEYXO0BABAGTlLlUwuM0qXWoNHn7zC1sCRrlx6TXQrKfpMBMpZA0kP9KlQEQRhGn8dZCVK18UQaZCNVbfP5PLaeAKOlHukl605f3tTPM5uaApyyZAofBdLv7v1AUleE5xfiYSvSJVroS3pZB6a5RZA9FR9UZBRp0VTr461TlvQZDZ&limit=48";
        String url2 = "https://graph.facebook.com/v3.2/463893653751145?fields=client_ad_accounts&access_token=EAAHgEYXO0BABAGcHX8cg9gA1jxA5YPEqk3fnHIJrJS72WttvJkZC0Mc4X9ZBlbUatsjAZCJwhvOMzpA3pm6lTh3pNabAXbLjLcEBCNAvteZCZAvCQQmB48LkcVgPT22uASHH4Fp6ke9cNIH2hgqj8MvNcxNSbAw9evgP0IfMEowZDZD";
        String url4 = "https://graph.facebook.com/v3.1/act_568836376631525/insights?fields=account_id%2Caccount_name%2Ccampaign_id%2Ccampaign_name%2Cadset_id%2Cadset_name%2Cad_id%2Cad_name%2Cdate_start%2Cdate_stop%2Cactions%2Caction_values%2Cclicks%2Cimpressions%2Creach%2Cspend&level=ad&time_increment=1&time_range=%7B%22since%22%3A%222019-04-26%22%2C%22until%22%3A%222019-04-29%22%7D&breakdowns=age%2Cgender&limit=1500";
        url3 = "https://graph.facebook.com/v3.3/act_712344008863677/advideos?fields=icon,permalink_url,source,picture,updated_time,created_time&access_token=EAANXwITyKJ4BAAc6e6yXZCWDGbAea11olgwN75ULr3pUk4XbwZBKmLZAVaXttPjkZCAbHEffrrgOlZAS4r5rSZB4UGNk3wMei2uDQS4ZCLCHTEWGm5hzVytncW5MrC47xuEiWJBwrqdZBw0J2jTeNqlgpzv3qCQto69esym21Fv0UQZDZD";
        HttpGet httpGet = new HttpGet(url3);
        try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) {
            HttpEntity httpEntity = httpResponse.getEntity();
            System.out.println("...............begin..............");
            System.out.println("status---->" + httpResponse.getStatusLine());
            System.out.println(EntityUtils.toString(httpEntity));
            System.out.println("...............end..............");

            /*String content = EntityUtils.toString(httpEntity, Consts.UTF_8);
            FacebookRepsponseSuccessDTO successDTO = JSONObject.parseObject(content, FacebookRepsponseSuccessDTO.class);
            for (FacebookInsightDTO dto : successDTO.getData()) {
                System.out.println(Constant.Common.HOUR.get(dto.getHourly_stats_aggregated_by_advertiser_time_zone())+"------------"+dto);
            }*/
        } catch (Exception e) {
            System.out.println(e);
        }
    }

}
